<template>
  <div class="user-list-container">
    <!-- 管理员控制台头部 -->
    <el-header class="admin-header">
      <div class="header-left">
        <h1>在线考试系统管理控制台</h1>
      </div>
      <div class="header-right">
        <el-dropdown>
          <span class="el-dropdown-link">
            <el-icon><UserFilled /></el-icon>
            <span class="username">{{ userInfo.username }}</span>
            <el-icon><ArrowDown /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="handleChangePassword">修改密码</el-dropdown-item>
              <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>
    
    <el-card class="user-card">
      <template #header>
        <div class="card-header">
          <h2>用户列表</h2>
          <div class="header-actions">
            <el-input v-model="searchQuery" placeholder="搜索用户名或真实姓名" prefix-icon="Search" style="width: 300px;" @keyup.enter="loadUsers"/>
            <el-button type="primary" @click="handleAddUser">添加用户</el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="usersData" style="width: 100%" v-loading="loading">
        <el-table-column prop="userId" label="用户ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="realName" label="真实姓名" width="120" />
        <el-table-column label="角色" width="100">
          <template #default="scope">
            <el-tag :type="getRoleType(scope.row.roleId)">{{ getRoleName(scope.row.roleId) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="scope">
            {{ scope.row.gender || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button 
              size="small" 
              :type="scope.row.status === 1 ? 'danger' : 'success'"
              @click="handleApproveUser(scope.row.userId, scope.row.status)"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button size="small" type="primary" @click="handleEditUser(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDeleteUser(scope.row.userId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 编辑用户弹窗 -->
    <el-dialog v-model="dialogVisible" title="编辑用户" width="500px" center>
      <el-form :model="editForm" label-width="80px" :rules="formRules" ref="formRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="editForm.realName" />
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="editForm.roleId" placeholder="请选择角色">
            <el-option label="管理员" value="1" />
            <el-option label="教师" value="2" />
            <el-option label="学生" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="editForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
            <el-radio label="未知">未知</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import { get, postJson, postForm } from '../../utils/api'
import { UserFilled, ArrowDown } from '@element-plus/icons-vue'

const router = useRouter()

const userInfo = ref({
  username: '',
  roleName: ''
})

onMounted(() => {
  // 从本地存储获取用户信息
  const storedUserInfo = localStorage.getItem('userInfo')
  if (storedUserInfo) {
    userInfo.value = JSON.parse(storedUserInfo)
  }
})

const handleLogout = async () => {
  try {
    // 调用后端登出接口，带上cookie
    await get('/user/logout')
    
    // 清除本地存储的用户信息
    localStorage.removeItem('user')
    
    // 跳转到登录页面
    router.push('/login')
    
    ElMessage.success('退出登录成功')
  } catch (error) {
    console.error('退出登录失败:', error)
    // 即使后端调用失败，也要清除本地状态并跳转
    localStorage.removeItem('user')
    router.push('/login')
    ElMessage.success('退出登录成功')
  }
}

const handleChangePassword = () => {
  router.push('/admin/change-password')
}

// 响应式数据
const usersData = ref<any[]>([])
const loading = ref(false)
const searchQuery = ref('')
const dialogVisible = ref(false)
const formRef = ref<FormInstance>()

// 编辑表单
const editForm = reactive({
  userId: 0,
  username: '',
  realName: '',
  roleId: 0,
  gender: '',
  phone: '',
  email: ''
})

// 表单验证规则
const formRules = reactive<FormRules>({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  roleId: [{ required: true, message: '请选择角色', trigger: 'change' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  email: [
    { pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
})

// 角色映射
const roleMap: Record<number, string> = {
  1: '管理员',
  2: '教师',
  3: '学生'
}

const roleTypeMap: Record<number, string> = {
  1: 'warning',
  2: 'primary',
  3: 'success'
}

// 获取角色名称
const getRoleName = (roleId: number) => {
  return roleMap[roleId] || '未知角色'
}

// 获取角色标签类型
const getRoleType = (roleId: number) => {
  return roleTypeMap[roleId] || 'info'
}

// 加载用户列表
const loadUsers = async () => {
  loading.value = true
  try {
    // 调用后端提供的接口
    const result = await get('/user/query')
    
    if (result.code === 200) {
      // 根据搜索条件过滤
      let filteredData = result.data || []
      if (searchQuery.value) {
        const keyword = searchQuery.value.toLowerCase()
        filteredData = filteredData.filter((user: any) => 
          (user.username && user.username.toLowerCase().includes(keyword)) ||
          (user.realName && user.realName.toLowerCase().includes(keyword))
        )
      }
      usersData.value = filteredData
    } else {
      ElMessage.error(result.msg || '获取用户列表失败')
      usersData.value = []
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('网络错误，请检查后端服务')
    usersData.value = []
  } finally {
    loading.value = false
  }
}

// 跳转到添加用户页面
const handleAddUser = () => {
  router.push('/admin/user/add')
}

// 打开编辑用户弹窗
const handleEditUser = (user: any) => {
  // 填充表单数据
  editForm.userId = user.userId
  editForm.username = user.username || ''
  editForm.realName = user.realName || ''
  editForm.roleId = user.roleId || 0
  editForm.gender = user.gender || '未知'
  editForm.phone = user.phone || ''
  editForm.email = user.email || ''
  dialogVisible.value = true
}

// 提交编辑表单
const submitEditForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    const result = await postJson('/user/update', editForm)
    
    if (result.code === 200) {
      ElMessage.success(result.msg || '修改成功')
      dialogVisible.value = false
      loadUsers() // 重新加载列表
    } else {
      ElMessage.error(result.msg || '修改失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('修改用户失败:', error)
    }
  }
}

// 审批用户（启用/禁用）
const handleApproveUser = async (userId: number, currentStatus: number) => {
  try {
    const confirmText = currentStatus === 1 ? '确定要禁用该用户吗？' : '确定要启用该用户吗？'
    await ElMessageBox.confirm(
      confirmText,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: currentStatus === 1 ? 'warning' : 'info'
      }
    )
    
    const result = await postForm('/user/approve', { id: userId })
    
    if (result.code === 200) {
      ElMessage.success(result.msg || '操作成功')
      loadUsers() // 重新加载列表
    } else {
      ElMessage.error(result.msg || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审批用户失败:', error)
    }
  }
}

// 删除用户
const handleDeleteUser = async (userId: number) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该用户吗？此操作不可撤销。',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const result = await postForm('/user/delete', { id: userId })
    
    if (result.code === 200) {
      ElMessage.success(result.msg || '删除成功')
      loadUsers() // 重新加载列表
    } else {
      ElMessage.error(result.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
    }
  }
}

// 初始加载
onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.admin-header {
  background-color: #1890ff;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.header-left h1 {
  font-size: 20px;
  margin: 0;
  font-weight: normal;
}

.el-dropdown-link {
  cursor: pointer;
  display: flex;
  align-items: center;
  color: white;
}

.username {
  margin: 0 8px;
}

/* 重置样式并确保容器填满整个屏幕 */
:deep(.el-card) {
  width: 100% !important;
  max-width: none !important;
  margin: 0 !important;
  border-radius: 0;
  border: none;
}

/* 外层容器完全填充满屏幕 */
.user-list-container {
  padding: 0 !important;
  min-height: 100vh;
  height: 100vh;
  background-color: #fff;
  width: 100vw !important;
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  overflow: hidden;
}

/* 卡片样式 */
.user-card {
  width: 100% !important;
  max-width: none !important;
  margin: 0 !important;
  padding: 0 !important;
  border: none;
  background-color: #fff;
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 头部样式 */
.card-header {
  padding: 20px;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

/* 表格样式 */
:deep(.el-table) {
  width: 100% !important;
  flex: 1;
}

:deep(.el-table__body-wrapper) {
  overflow-y: auto;
}

/* 弹窗样式 */
:deep(.el-dialog__body) {
  max-height: 60vh;
  overflow-y: auto;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}
</style>

/* 全局样式重置，确保整个页面背景一致 */
<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body, html {
  width: 100% !important;
  height: 100% !important;
  background-color: #fff !important;
  overflow: hidden;
}

#app {
  width: 100% !important;
  height: 100% !important;
  background-color: #fff !important;
}
</style>